package one.stand.service;

import one.stand.entity.TokenEntity;
import one.stand.mapper.*;
import one.stand.model.SeeRecordModel;
import one.stand.util.RandomUtil;
import one.stand.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Administrator
 */
public class BaseService {

    protected static Logger log = LoggerFactory.getLogger(Class.class);

    /**
     * 用户信息
     */
    @Autowired
    protected UserMapper userMapper;
    /**
     * 用户收藏信息
     */
    @Autowired
    protected CollectionMapper collectionMapper;
    /**
     * 用户地址
     */
    @Autowired
    protected AddressMapper addressMapper;
    /**
     * 购物车
     */
    @Autowired
    protected ShopcartMapper shopcartMapper;
    /**
     * 订单
     */
    @Autowired
    protected OrdersMapper ordersMapper;
    /**
     * 订单明细
     */
    @Autowired
    protected OrderinfoMapper orderinfoMapper;
    /**
     * 用户支付记录信息
     */
    @Autowired
    protected PaymentRecordMapper paymentRecordMapper;
    /**
     * 用户支付记录信息
     */
    @Autowired
    protected RefundRecordMapper refundRecordMapper;
    /**
     * 商品信息
     */
    @Autowired
    protected GoodsMapper goodsMapper;
    /**
     * 商品规格信息
     */
    @Autowired
    protected GoodSpecMapper goodSpecMapper;
    /**
     * 商品拼团配置
     */
    @Autowired
    protected GoodsAssembleMapper goodsAssembleMapper;
    /**
     * 用户拼团
     */
    @Autowired
    protected AssembleMapper assembleMapper;
    /**
     * 公司信息
     */
    @Autowired
    protected CompanyMapper companyMapper;
    /**
     * 商品分类信息
     */
    @Autowired
    protected GoodstypeMapper goodstypeMapper;
    /**
     * 名片
     */
    @Autowired
    protected BusinessCardMapper businessCardMapper;

    /**
     * 名片视频
     */
    @Autowired
    protected BusinessCardVideoMapper businessCardVideoMapper;
    /**
     * 名片查看记录
     */
    @Autowired
    protected SeeRecordMapper seeRecordMapper;
    /**
     * 公司动态
     */
    @Autowired
    protected DynamicMapper dynamicMapper;
    /**
     * 公司官网
     */
    @Autowired
    protected WebsiteMapper websiteMapper;
    /**
     * 用户需求表
     */

    @Autowired
    protected DemandMapper demandMapper;
    /**
     * 公司招聘表
     */
    @Autowired
    protected CompanyRecruitMapper companyRecruitMapper;
    /**
     * 点赞表
     */
    @Autowired
    protected ThumbsMapper thumbsMapper;

    /**
     * 评论表
     */
    @Autowired
    protected CommentMapper commentMapper;

    /**
     * 客户关系
     */
    @Autowired
    protected CustomerMapper customerMapper;

    /**
     * 客户关系与标签
     */
    @Autowired
    protected CustomerLabelMapper customerLabelMapper;

    /**
     * 客户标签列表
     */
    @Autowired
    protected CompanyCustomerLableMapper companyCustomerLableMapper;

    @Autowired
    protected IndustryMapper industryMapper;

    /**
     * 浏览记录
     */
    @Autowired
    protected FollowRecordMapper followRecordMapper;

    /**
     * 录入成交金额
     */
    @Autowired
    protected InputDealMoneyMapper inputDealMoneyMapper;

    /**
     * 企业成员本月目标
     */
    @Autowired
    protected UserTaskMapper userTaskMapper;

    /**
     * 电话拨打次数
     */
    @Autowired
    protected CallsPhoneRecordMapper callsPhoneRecordMapper;

    /**
     * 商品分析记录
     */
    @Autowired
    protected GoodsForwardRecordMapper goodsForwardRecordMapper;

    /**
     * 文章分析记录
     */
    @Autowired
    protected DynamicForwardRecordMapper dynamicForwardRecordMapper;

    /**
     * 咨询记录表
     */
    @Autowired
    protected ConsultRecordMapper consultRecordMapper;

    /**
     * 公司服务表
     */
    @Autowired
    protected CompanyServiceMapper companyServiceMapper;

    /**
     * 微信推送模板表
     */
    @Autowired
    protected WxNoticeMapper wxNoticeMapper;

    /**
     *
     */
    @Autowired
    protected AdminMapper adminMapper;

    /**
     * 小程序代码版本管理
     */
    @Autowired
    protected VersionMapper versionMapper;

    /**
     * 菜单表
     */
    @Autowired
    protected MenuMapper menuMapper;

    /**
     * 操作记录
     */
    @Autowired
    protected AdminRecordMapper adminRecordMapper;

    /**
     * 公司视频
     */
    @Autowired
    protected CompanyVideoMapper companyVideoMapper;

    /**
     *
     */
    @Autowired
    protected RoyaltyRecordMapper royaltyRecordMapper;

    @Autowired
    protected CompanyTransferMapper companyTransferMapper;

    @Autowired
    protected CompanyRoyaltyMapper companyRoyaltyMapper;

    @Autowired
    protected GlobalConfigurationMapper globalConfigurationMapper;

    @Autowired
    protected CompanyAccountMapper companyAccountMapper;

    @Autowired
    protected CompanyVersionMapper companyVersionMapper;

    @Autowired
    protected NoticeMapper noticeMapper;

    @Autowired
    protected ProductsTypeMapper productsTypeMapper;

    @Autowired
    protected ProductsMapper productsMapper;

    @Autowired
    protected ProductsPhotoMapper productsPhotoMapper;

    @Autowired
    protected AppointmentMapper appointmentMapper;

    @Autowired
    protected CompanyPhotoMapper companyPhotoMapper;

    @Autowired
    protected UserCommonMapper userCommonMapper;

    @Autowired
    protected UserLevelMapper userLevelMapper;

    @Autowired
    protected SunCodeMapper sunCodeMapper;

    @Autowired
    protected RedisUtil redisUtil;

    @Autowired
    protected CompanyCouponMapper companyCouponMapper;
    @Autowired
    protected UserCouponMapper userCouponMapper;
    protected String arraySymbol=",";

    protected static Integer r = 0;

    protected final static Integer ONE = 1;

    protected final static Integer TWO = 2;

    public static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static SimpleDateFormat formatte = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    public static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    public final String HUNDRED = "100";

    /**
     * 最大分销比例之和
     */
    public final static Integer maxRatio = 50;

    /**
     * 获取当前时间
     *
     * @return
     */
    public Date currentDate() {
        return new Date();
    }

    public String getDay() {
        return formatter.format(new Date());
    }

    /**
     * 金额除100 并保留两位小数
     *
     * @param money
     * @return String
     * */
    public String getMoneyString(String money){
        if(StringUtils.isEmpty(money) || Integer.parseInt(money) <= 0){
            return "0";
        }
        BigDecimal a = new BigDecimal(money);
        BigDecimal b = new BigDecimal(HUNDRED);
        return a.divide(b, 2, RoundingMode.HALF_UP).toString();
    }

    /**
     * 添加查看记录
     *
     * @param userId    查看人ID
     * @param cardId    查看入口名片ID/查看对象ID
     * @param companyId 公司ID
     * @param seeType   1:名片，2:产品，3：官网,4:查看文章
     * @param itmeId    查看对象ID
     * @return
     */
    public Integer addSeeRecord(Integer userId, Integer cardId, Integer companyId, Integer seeType, Integer itmeId) {
        //添加查看记录
        SeeRecordModel model = new SeeRecordModel();
        if (null != userId) {
            model.setUserId(userId);
        }
        if (null != companyId) {
            model.setCompanyId(companyId);
        }
        if (null != seeType) {
            model.setSeeType(seeType);
        }
        if (null != itmeId) {
            model.setItmeId(itmeId);
        }
        if (null != cardId) {
            model.setCardId(cardId);
        }
        model.setRanking(seeRecordMapper.selectRanking(model) + 1);
        model.setCreateTime(currentDate());
        seeRecordMapper.insertSelective(model);
        businessCardMapper.addSeeNum(cardId);
        return model.getRecordId();
    }

    /**
     * 计算时间
     *
     * @param deliveryTime    配送时间(发货时间）
     * @return
     */
    public String getSurplusDeliveryTime(Date deliveryTime) {
        if (null == deliveryTime) {
            return "";
        }
        Calendar ca = Calendar.getInstance();
        ca.setTime(deliveryTime);
        ca.add(Calendar.DATE, 15);
        Date date = ca.getTime();

        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = date.getTime() - currentDate().getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return new StringBuffer("离收货还有").append(day).append("天").append(hour).append("时自动确认").toString();
    }

    /**
     * 总后台（admin）创建登录token
     *
     * @param id
     * @return
     */
    public TokenEntity createToken(Long id) {
        TokenEntity tokenModel = new TokenEntity();
        tokenModel.setId(id);
        tokenModel.setToken(RandomUtil.generateString(10) + "_" + id);
        tokenModel.setLogintime(currentDate());
        return tokenModel;
    }

    /**
     * 比较两个时间大小
     *
     * @param newDate
     * @param oldDate
     * @return
     */
    public Boolean compareDate(Date newDate, Date oldDate){
        return newDate.compareTo(oldDate) >= 0 ? true : false;
    }

    /**
     * 给一个指定时间和当前时间比较，相差多少天
     *
     * @param end
     * @return
     */
    public Long days(Date end){
        if(end == null){
            return 0L;
        }
        Instant instant = end.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDate endDate = instant.atZone(zoneId).toLocalDate();
        return LocalDate.now().until(endDate, ChronoUnit.DAYS);
    }

    /**
     * 金额除100 并保留两位小数
     *
     * @param moeny
     * @return Double
     */
    public Double money(Integer moeny){
        if(moeny == null || moeny <= 0){
            return 0.0;
        }
        BigDecimal bg = new BigDecimal(moeny);
        BigDecimal hj = new BigDecimal(100);
        return bg.divide(hj,2, RoundingMode.HALF_UP).doubleValue();
    }

    /**
     * 返回字符串
     *
     * @param obj
     * @return
     */
    public String getObjectString(Object obj) {
        if (obj == null || org.apache.commons.lang3.StringUtils.isBlank(obj + "")) {
            return " ";
        }
        return obj.toString();
    }

    /**
     * 根据当前时间，添加或减去指定的时间量。例如，要从当前日历时间减去 5 天，可以通过调用以下方法做到这一点：
     * add(Calendar.DAY_OF_MONTH, -5)。
     * @param date 指定时间
     * @param num  为时间添加或减去的时间天数
     * @return
     */
    public Date getBeforeOrAfterDate(Date date, int num) {
        //获取日历
        Calendar calendar = Calendar.getInstance();
        //当date的值是当前时间，则可以不用写这段代码。
        calendar.setTime(date);
        calendar.add(Calendar.DATE, num);
        //把日历转换为Date
        return calendar.getTime();
    }

    /**
     * 根据时间戳生产支付编号
     *
     * @return
     */
    public String getPayNo() {
        return "PAY" + System.currentTimeMillis() + "" + (int) (1 + Math.random() * (9999));
    }

    /**
     * 根据时间戳生产退款订单编号
     *
     * @return
     */
    public String getRefundNo() {
        return "TK" + System.currentTimeMillis() + "" + (int) (1 + Math.random() * (9999));
    }

    /**
     * 得到商品名称（有长度限制）
     *
     * @return
     */
    public String getLimitGoodsName(String goodsName){
        if(org.apache.commons.lang3.StringUtils.isBlank(goodsName)){
            return "";
        }
        if(goodsName.length() <= 20){
            return goodsName;
        }
        return goodsName.substring(0,20) + "...";
    }

    /**
     * 根据时间戳生产订单编号
     *
     * @return
     */
    public String getOrderNo() {
        return "YL" + System.currentTimeMillis() + "" + (int) (1 + Math.random() * (9999));
    }

    /**
     * 根据时间戳生产提现编号
     *
     * @return
     */
    public String getRecordNo() {
        return "TX" + System.currentTimeMillis() + "" + (int) (1 + Math.random() * (9999));
    }

    /**
     * 对用户名称进行去重和base64转义
     *
     * @param doThumbsName
     * @return
     */
    public String doThumbsName(String doThumbsName){
        if(org.apache.commons.lang3.StringUtils.isBlank(doThumbsName)){
            return "";
        }
        Set<String> set = new HashSet<>();
        for(String str : doThumbsName.split(",")){
            set.add(str);
        }
        StringBuffer stringBuffer = new StringBuffer();
        for(String val : set){
            stringBuffer.append(new String(java.util.Base64.getDecoder().decode(val))).append(",");
        }
        return stringBuffer.toString().substring(0,stringBuffer.length() - 1);
    }
}
